'use strict';

let DEFAULT_INTERVAL = 1000 / 60;

// 初始状态
let STATE_INITIAL = 0;
// 开始状态
let STATE_START = 1;
// 停止状态
let STATE_STOP = 2;  

/**
 * raf
 */
var requestAnimationFrame = (function() {
    return window.requestAnimationFrame ||
        window.webkitRequestAnimationFrame||
        window.mozRequestAnimationFrame ||
        window.oRequestAnimationFrame ||
        function (callback) {
            return window.setTimeout(callback, callback.interval ||
                DEFAULT_INTERVAL);
        };
})();

let cancelAnimationFrame = (function(){
    return window,cancelAnimationFrame ||
        window.webkitCancelAnimationFrame ||
        window.mozCancelRequestAnimationFrame ||
        function (id) {
            return window.clearTimeout(id);
        };

})();

/**
 * Timeline 时间轴类
 * @constructor
 */
function Timeline() {
    this.animationHandler = 0;
    this.state = STATE_INITIAL;
}
/**
 * 时间轴上每一次回调执行的函数
 * @param {从动画开始到当前执行的时间} time 
 */
Timeline.prototype.onenterframe = function(time) {

};

/**
 * 动画开始
 * @param {每一次回调的间隔时间} interval 
 */
Timeline.prototype.start = function(interval) {
    if(this.state === STATE_START){
        return;
    }
    this.state = STATE_START;

    this.interval = interval || DEFAULT_INTERVAL;
    startTimeline(this, + new Date());
};

/**
 * 动画暂停
 */
Timeline.prototype.stop = function() {
    if(this.state !== STATE_START){
        return;
    }
    this.state = STATE_STOP;

    // 如果动画开始过，记录动画所经历的时间
    if(this.startTime){
        this.dur = +new Date() - this.startTime;
    }
    cancelAnimationFrame(this.animationHandler);
};

/**
 * 重新开始动画
 */
Timeline.prototype.restart = function() {
    if(this.state === STATE_START){
        return;
    }
    if(!this.dur || !this.interval){
        return;
    }
    this.state = STATE_START;
    // 无缝连接动画
    startTimeline(this, +new Date() - this.dur);
};

/**
 * 时间轴动画启动函数
 * @param {时间轴实例} timeline 
 * @param {动画开始时间} startTime 
 */
function startTimeline(timeline, startTime) {
    timeline.startTime = startTime;
    nextTick.interval = timeline.interval;
    // 记录上一次回调的时间戳
    let lastTick = +new Date();

    // 每一帧的执行函数
    function nextTick() {
        let now = + new Date();

        timeline.animationHandler = requestAnimationFrame(nextTick);

        // 如果时间差大于设置的时间间隔，表示这次可以执行回调
        if(now - lastTick >= timeline.interval){
            timeline.onenterframe(now - startTime);
            lastTick = now;
        }
    }
}

module.export = Timeline;